using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Text.RegularExpressions;
using MediaPortal.Configuration;
using MediaPortal.Dialogs;
using MediaPortal.GUI.Library;
using MediaPortal.Player;
using MediaPortal.Playlists;

namespace OnlineVideos
{
    public class GUIOnlineVideos : GUIWindow, ISetupForm
    {
        #region Skin Controls
        [SkinControlAttribute(2)]
        protected GUIButtonControl btnViewAs = null;
        [SkinControlAttribute(3)]
        protected GUIButtonControl btnNext = null;
        [SkinControlAttribute(4)]
        protected GUIButtonControl btnPrevious = null;
        [SkinControlAttribute(5)]
        protected GUISelectButtonControl btnMaxResult = null;
        [SkinControlAttribute(6)]
        protected GUISelectButtonControl btnOrderBy = null;
        [SkinControlAttribute(7)]
        protected GUISelectButtonControl btnTimeFrame = null;
        [SkinControlAttribute(8)]
        protected GUIButtonControl btnUpdate = null;        
        [SkinControlAttribute(9)]
        protected GUISelectButtonControl btnSearchCategories = null;
        [SkinControlAttribute(10)]
        protected GUIButtonControl btnSearch = null;
        [SkinControlAttribute(11)]
        protected GUIButtonControl btnFavorite = null;
        [SkinControlAttribute(50)]
        protected GUIFacadeControl facadeView = null;
        [SkinControlAttribute(1)]
        protected GUIImage logoImage = null;

#endregion
        #region Current Facade View
        protected View currentView = View.List;
        protected View currentSiteView = View.List;
        protected View currentVideoView = View.Icons;
#endregion
        #region state variables
        private Dictionary<String, SiteSettings> moSiteList = new Dictionary<String, SiteSettings>();
        private String msSelectedSiteId;
        private String msSelectedCategoryValue;
        private String msSelectedCategoryName;
        private VideoInfo moSelectedVideo;
        private State _CurrentState = State.home;
        private List<VideoInfo> moCurrentVideoList = new List<VideoInfo>();
        private List<VideoInfo> moCurrentTrailerList = new List<VideoInfo>();
        private int miSelectedIndex = 0;
        private bool mbPlayFullscreen = true;
        private bool showingFavorites = false;
        private SiteUtilBase SelectedSite;
        #endregion
        #region filter variables
        private List<int> moSupportedMaxResultList;
        private Dictionary<String, String> moSupportedOrderByList;
        private Dictionary<String, String> moSupportedTimeFrameList;
        private Dictionary<String, String> moSupportedSearchCategoryList;

        //selected values
        private int miMaxResult;
        private String msOrderBy = String.Empty;
        private String msTimeFrame = String.Empty;
        
        //selected indices
        private int SelectedMaxResultIndex;
        private int SelectedOrderByIndex;
        private int SelectedTimeFrameIndex;
        private int SelectedSearchCategoryIndex;
        #endregion        
        #region search variables
        private String msLastSearchQuery;
        private String msLastSearchCategory;
        private bool mbSearchMode = false;
        #endregion
        private String[] msFilterArray;       

        public enum State
        {
            home = 0,
            categories = 1,
            videos = 2,
            info = 3
        }
        public enum View
        {
            List = 0,
            Icons = 1,
            LargeIcons = 2

        }
        public class SiteSettings
        {
            public String name;
            public String id;
            public string username;
            public string password;
            public bool confirmAge;
            public bool enabled;
            public Dictionary<String, RssLink> RssList = new Dictionary<String, RssLink>();
            public String toString()
            {
                return "name";
            }
        }
        public class RssLink : IComparer<RssLink>
        {
            public String name;
            public Boolean isDynamic = false;
            public String url;

            #region IComparer Members
            public int Compare(RssLink x, RssLink y)
            {
                return x.name.CompareTo(y.name);
            }

            #endregion
        }
        public class VideoInfo
        {
            public String Title;
            public String Title2;
            public String Description = "";
            public String VideoUrl = "";
            public String ImageUrl = "";
            public String Length;
            public String Tags = "";
            public Object Other;
            public string SiteID = "";
            public int VideoID;
            public VideoInfo()
            {
                VideoID = -1;
            }
            public override string ToString()
            {
                return String.Format("Title:{0}\nDesc:{1}\nVidUrl:{2}\nImgUrl:{3}\nLength:{4}\nTags:{5}", Title, Description, VideoUrl, ImageUrl, Length, Tags);
            }
        }
        public class FavoriteVideoInfo : VideoInfo
        {
            public String videoId;
        }
        public static string PluginNameStatic()
        {
            return "Online Videos";

        }
        public string PluginName()
        {
            return PluginNameStatic();
        }

        // Returns the description of the plugin is shown in the plugin menu
        public string Description()
        {
            return "Browse videos from various online sites such as Youtube, Apple Trailers";
        }
        // Returns the author of the plugin which is shown in the plugin menu

        public string Author()
        {
            return "GregMac45";
        }

        // show the setup dialog

        public void ShowPlugin()
        {
            System.Windows.Forms.Form setup = new Configuration();
            setup.ShowDialog();
        }

        // Indicates whether plugin can be enabled/disabled

        public bool CanEnable()
        {
            return true;
        }

        // get ID of windowplugin belonging to this setup

        public int GetWindowId()
        {
            return GetID;
        }

        // Indicates if plugin is enabled by default;

        public bool DefaultEnabled()
        {
            return true;
        }

        // indicates if a plugin has its own setup screen

        public bool HasSetup()
        {
            return true;
        }

        public bool GetHome(out string strButtonText, out string strButtonImage, out string strButtonImageFocus, out string strPictureImage)
        {
            strButtonText = PluginName();

            strButtonImage = String.Empty;

            strButtonImageFocus = String.Empty;

            strPictureImage = "hover_onlinevideos.png";

            return true;
        }
        public bool ShowDefaultHome()
        {
            return true;
        }

        public override int GetID
        {
            get
            {
                return 4755;
            }
            set
            {
            }
        }
        public override bool Init()
        {
            bool result = Load(GUIGraphicsContext.Skin + @"\myonlinevideos.xml");
            LoadSettings();
            return result;

        }

        protected override void OnPageLoad()
        {
            Log.Info("OnPageLoad. CurrentState:" + _CurrentState);
            if (_CurrentState == State.home)
            {
                DisplaySites();
                SwitchView();
                GUIControl.FocusControl(GetID, facadeView.GetID);
            }
            else if (_CurrentState == State.categories)
            {
                DisplayCategories();
            }
            else if (_CurrentState == State.videos)
            {
                DisplayCategoryVideos();
                facadeView.SelectedListItemIndex = miSelectedIndex;
            }
            else
            {
                DisplayVideoDetails(moSelectedVideo);
            }
            UpdateViewState();
        }
        protected override void OnShowContextMenu()
        {
            int liSelected = facadeView.SelectedListItemIndex - 1;
            if (liSelected < 0 || msSelectedSiteId == "99" || _CurrentState == State.home || _CurrentState == State.categories || (msSelectedSiteId == "15" && _CurrentState == State.videos))
            {
                return;
            }
            GUIListItem loListItem = facadeView.SelectedListItem;
            GUIDialogMenu dlgSel = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
            dlgSel.Reset();

            if (dlgSel != null)
            {
                dlgSel.Add("Play All");

                if (showingFavorites == false)
                {
                    dlgSel.Add("Add to favorites");
                }
                else
                {
                    dlgSel.Add("Remove from favorites");
                }

                if (msSelectedSiteId == "1")
                {
                    dlgSel.Add("Related Videos"); // Related Videos
                }
                if (String.IsNullOrEmpty(OnlineVideoSettings.getInstance().msDownloadDir) == false)
                {
                    dlgSel.Add("Save"); // Save
                }
            }
            dlgSel.DoModal(GetID);
            int liSelectedIdx = dlgSel.SelectedId;
            VideoInfo loSelectedVideo;
            if (_CurrentState == State.videos)
            {
                loSelectedVideo = moCurrentVideoList[liSelected];
            }
            else
            {
                loSelectedVideo = moCurrentTrailerList[liSelected];
            }
            switch (liSelectedIdx)
            {
                case 1:
                    playAll();
                    break;
                case 2:
                    AddOrRemoveFavorite(loSelectedVideo);
                    break;
                case 3:
                    if (msSelectedSiteId == "1")
                    {
                        getRelatedVideos(loSelectedVideo);
                    }
                    else
                    {
                        SaveVideo(loSelectedVideo);
                    }
                    break;
                case 4:
                    SaveVideo(loSelectedVideo);
                    break;

            }
            base.OnShowContextMenu();
        }
        public override void OnAction(Action action)
        {
            if (action.wID == Action.ActionType.ACTION_PREVIOUS_MENU && _CurrentState != State.home)
            {
                OnShowPreviousMenu2();
                return;

            }
            base.OnAction(action);
        }
        public override bool OnMessage(GUIMessage message)
        {
            switch (message.Message)
            {
                case GUIMessage.MessageType.GUI_MSG_WINDOW_INIT:
                    {
                        base.OnMessage(message);
                        btnSearchCategories.RestoreSelection = false;
                        btnOrderBy.RestoreSelection = false;
                        btnTimeFrame.RestoreSelection = false;
                        btnMaxResult.RestoreSelection = false;
                        return true;
                    }
            }
            /*
            switch(message.message){
            case if(1==1){
                GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_ITEM_SELECTED, GetID, 0, iControl, 0, 0, null);
						OnMessage(msg);
            }
            }
             */
            return base.OnMessage(message);
        }
        protected override void OnClicked(int controlId, GUIControl control, Action.ActionType actionType)
        {
            if (control == facadeView && actionType == Action.ActionType.ACTION_SELECT_ITEM)
            {

                if (_CurrentState == State.home)
                {
                    msSelectedSiteId = facadeView.SelectedListItem.Path;
                    SelectedSite = SiteUtilFactory.getSiteUtil(msSelectedSiteId);
                    DisplayCategories();
                    _CurrentState = State.categories;
                }
                else if (_CurrentState == State.categories)
                {
                    if (facadeView.SelectedListItemIndex == 0)
                    {
                        OnShowPreviousMenu2();
                    }
                    else
                    {
                        msSelectedCategoryValue = facadeView.SelectedListItem.Path;
                        msSelectedCategoryName = facadeView.SelectedListItem.Label;
                        _CurrentState = State.videos;
                        refreshVideoList();
                    }
                }
                else if (_CurrentState == State.videos)
                {
                    Log.Info("Set the stopDownload to true 2");
                    ImageDownloader._stopDownload = true;
                    if (facadeView.SelectedListItemIndex == 0)
                    {
                        OnShowPreviousMenu2();
                    }

                    else
                    {
                        miSelectedIndex = facadeView.SelectedListItemIndex;
                        if (msSelectedSiteId == "15")
                        {
                            _CurrentState = State.info;
                            DisplayVideoDetails(moCurrentVideoList[facadeView.SelectedListItemIndex - 1]);
                        }
                        else
                        {
                            //play the video
                            Play(moCurrentVideoList[facadeView.SelectedListItemIndex - 1]);
                        }
                    }
                }
                else if (_CurrentState == State.info)
                {
                    ImageDownloader._stopDownload = true;
                    if (facadeView.SelectedListItemIndex == 0)
                    {
                        OnShowPreviousMenu2();
                    }
                    else
                    {
                        miSelectedIndex = facadeView.SelectedListItemIndex;
                        //play the video
                        Play(moCurrentTrailerList[facadeView.SelectedListItemIndex - 1]);
                    }
                }
                UpdateViewState();
            }

            else if (control == btnViewAs)
            {
                ChangeFacadeView();
            }

            else if (control == btnNext)
            {
                moCurrentVideoList = null;
                moCurrentVideoList = SiteUtilFactory.getSiteUtil(msSelectedSiteId).getNextPageVideos();
                DisplayCategoryVideos();
                UpdateViewState();
            }
            else if (control == btnPrevious)
            {
                moCurrentVideoList = null;
                moCurrentVideoList = SiteUtilFactory.getSiteUtil(msSelectedSiteId).getPreviousPageVideos();
                DisplayCategoryVideos();
                UpdateViewState();
            }
            else if (control == btnMaxResult)
            {
                GUIControl.SelectItemControl(GetID, btnMaxResult.GetID, btnMaxResult.SelectedItem);
            }
            else if (control == btnOrderBy)
            {
                GUIControl.SelectItemControl(GetID, btnOrderBy.GetID, btnOrderBy.SelectedItem);
            }
            else if (control == btnTimeFrame)
            {
                GUIControl.SelectItemControl(GetID, btnTimeFrame.GetID, btnTimeFrame.SelectedItem);
            }
            else if (control == btnUpdate)
            {
                GUIControl.UnfocusControl(GetID, btnUpdate.GetID);
                FilterVideos();
                UpdateViewState();
            }
            else if (control == btnSearchCategories)
            {
                GUIControl.SelectItemControl(GetID, btnSearchCategories.GetID, btnSearchCategories.SelectedItem);
            }
            else if (control == btnSearch)
            {
                //GUIControl.UnfocusControl(GetID, btnSearch.GetID);
                String query = String.Empty;
                GetUserInputString(ref query);
                GUIControl.FocusControl(GetID, facadeView.GetID);
                if (query != String.Empty)
                {
                    msLastSearchQuery = query;

                    SearchVideos(query);
                    msSelectedCategoryName = "Search";

                    _CurrentState = State.videos;
                    UpdateViewState();
                }
            }
            else if ((control == btnFavorite))
            {
                GUIControl.FocusControl(GetID, facadeView.GetID);
                //GUIControl.UnfocusControl(GetID, btnFavorite.GetID);
                DisplayFavoriteVideos();
                _CurrentState = State.videos;
                UpdateViewState();
            }

            base.OnClicked(controlId, control, actionType);
        }

        private void OnShowPreviousMenu2()
        {
            Log.Info("OnShowPreviousMenu2. _CurrentState:" + _CurrentState);
            if (_CurrentState == State.categories)
            {
                DisplaySites();
                _CurrentState = State.home;
            }
            else if (_CurrentState == State.videos)
            {
                Log.Info("Set the stopDownload to true 3");
                ImageDownloader._stopDownload = true;

                DisplayCategories();
                _CurrentState = State.categories;
                showingFavorites = false;
                mbSearchMode = false;
            }
            else if (_CurrentState == State.info)
            {
                ImageDownloader._stopDownload = true;
                DisplayCategoryVideos();
                SwitchView();
                btnViewAs.Visible = true;
                _CurrentState = State.videos;
            }
            DisplayVideoInfo(null);
            UpdateViewState();

        }
        protected override void OnPageDestroy(int newWindowId)
        {
            // Save view
            using (MediaPortal.Profile.Settings xmlwriter = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml")))
            {
                xmlwriter.SetValue("onlinevideos", "siteview", (int)currentSiteView);
                xmlwriter.SetValue("onlinevideos", "videoview", (int)currentVideoView);
            }
            base.OnPageDestroy(newWindowId);
        }
        private void item_OnItemSelected(GUIListItem item, GUIControl parent)
        {
            GUIFilmstripControl filmstrip = parent as GUIFilmstripControl;
            if (filmstrip == null)
                return;
            filmstrip.InfoImageFileName = item.ThumbnailImage;
        }
        #region new methods
        private void LoadSettings()
        {
            using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml")))
            {
                currentSiteView = (View)xmlreader.GetValueAsInt("onlinevideos", "siteview", (int)View.List);
                currentVideoView = (View)xmlreader.GetValueAsInt("onlinevideos", "videoview", (int)View.Icons);
                SwitchView();
            }
            OnlineVideoSettings settings = OnlineVideoSettings.getInstance();
            msFilterArray = settings.msFilterArray;
            moSiteList = settings.moSiteList;
            //create a favorites site
            SiteSettings SelectedSite = new SiteSettings();
            SelectedSite.id = "100";
            SelectedSite.name = "Favorites";
            SelectedSite.enabled = true;
            RssLink cat = new RssLink();
            cat.isDynamic = true;
            cat.name = "dynamic";
            cat.url = "favorites";
            SelectedSite.RssList.Add("dynamic", cat);
            moSiteList.Add("100", SelectedSite);

            if (!String.IsNullOrEmpty(settings.msDownloadDir))
            {
                try
                {
                    if (System.IO.Directory.Exists(settings.msDownloadDir) == false)
                    {
                        System.IO.Directory.CreateDirectory(settings.msDownloadDir);
                    }
                }
                catch (Exception e)
                {
                    Log.Error("Failed to create download dir");
                    Log.Error(e);
                }
                //add a downloaded videos site
                SelectedSite = new SiteSettings();
                SelectedSite.id = "99";
                SelectedSite.name = "Downloaded Videos";
                SelectedSite.enabled = true;
                cat = new RssLink();
                cat.name = "All";
                cat.url = settings.msDownloadDir;
                SelectedSite.RssList.Add(cat.name, cat);
                moSiteList.Add("99", SelectedSite);
            }
            try
            {
                if (System.IO.Directory.Exists(settings.msThumbLocation) == false)
                {
                    Log.Info("Thumb dir does not exist.");
                    System.IO.Directory.CreateDirectory(settings.msThumbLocation);
                    Log.Info("thumb dir created");
                }
            }
            catch (Exception e)
            {
                Log.Error("Failed to create thumb dir");
                Log.Error(e);
            }
        }
        private void DisplaySites()
        {
            GUIControl.ClearControl(GetID, facadeView.GetID);

            GUIListItem loListItem;
            String image;
            foreach (SiteSettings SelectedSite in moSiteList.Values)
            {
                if (SelectedSite.enabled)
                {

                    loListItem = new GUIListItem(SelectedSite.name);
                    loListItem.Path = SelectedSite.id;
                    image = GUIGraphicsContext.Skin + @"/Media/OnlineVidSiteIcon" + SelectedSite.id + ".png";
                    if (System.IO.File.Exists(image))
                    {
                        loListItem.ThumbnailImage = GUIGraphicsContext.Skin + @"/Media/OnlineVidSiteIcon" + SelectedSite.id + ".png";
                        loListItem.IconImage = GUIGraphicsContext.Skin + @"/Media/OnlineVidSiteIcon" + SelectedSite.id + ".png";
                        loListItem.IconImageBig = GUIGraphicsContext.Skin + @"/Media/OnlineVidSiteIcon" + SelectedSite.id + ".png";
                        loListItem.OnItemSelected += new MediaPortal.GUI.Library.GUIListItem.ItemSelectedHandler(item_OnItemSelected);
                    }
                    else
                    {
                        loListItem.IsFolder = true;
                        MediaPortal.Util.Utils.SetDefaultIcons(loListItem);
                    }
                    facadeView.Add(loListItem);
                }
            }
            SelectedMaxResultIndex = -1;
            SelectedOrderByIndex = -1;
            SelectedSearchCategoryIndex = -1;
            SelectedTimeFrameIndex = -1;
            GUIPropertyManager.SetProperty("#header.image", "");
        }
        private void DisplayCategories()
        {
            GUIControl.ClearControl(GetID, facadeView.GetID);
            GUIListItem loListItem;
            loListItem = new GUIListItem("..");
            loListItem.IsFolder = true;
            MediaPortal.Util.Utils.SetDefaultIcons(loListItem);
            facadeView.Add(loListItem);
            SiteSettings SelectedSiteSettings = moSiteList[msSelectedSiteId];

            List<RssLink> dynamicCategories = SelectedSite.getDynamicCategories();
            foreach (RssLink loCat in SelectedSiteSettings.RssList.Values)
            {
                if (loCat.isDynamic)
                {
                    Log.Info("Looking for dynamic categories for {0}", loCat.name);
                    List<RssLink> loNewCatList = SelectedSite.getDynamicCategories(loCat.url);
                    Log.Info("Found {0} dynamic categoties.", loNewCatList.Count);
                    foreach (RssLink loNewCat in loNewCatList)
                    {
                        loListItem = new GUIListItem(loNewCat.name);
                        loListItem.Path = loNewCat.url;
                        loListItem.IsFolder = true;
                        MediaPortal.Util.Utils.SetDefaultIcons(loListItem);
                        facadeView.Add(loListItem);
                    }
                }
                else
                {
                    loListItem = new GUIListItem(loCat.name);
                    loListItem.Path = loCat.url;
                    loListItem.IsFolder = true;
                    MediaPortal.Util.Utils.SetDefaultIcons(loListItem);
                    facadeView.Add(loListItem);
                }
            }
            if (dynamicCategories != null)
                foreach (RssLink loCat in dynamicCategories)
                {
                    loListItem = new GUIListItem(loCat.name);
                    loListItem.Path = loCat.url;
                    loListItem.IsFolder = true;
                    MediaPortal.Util.Utils.SetDefaultIcons(loListItem);
                    facadeView.Add(loListItem);
                }
        }
        //private void DisplayCategoryVideos(bool fbRefresh)
        //{
        //    DisplayCategoryVideos(fbRefresh, false, String.Empty);

        //}
        private void FilterVideos()
        {
            miMaxResult = -1;
            SelectedMaxResultIndex = btnMaxResult.SelectedItem;
            SelectedOrderByIndex = btnOrderBy.SelectedItem;
            SelectedTimeFrameIndex = btnTimeFrame.SelectedItem;
            try
            {
                miMaxResult = Int32.Parse(btnMaxResult.SelectedLabel);
            }
            catch (Exception) { }
            msOrderBy = String.Empty;
            try
            {
                msOrderBy = moSupportedOrderByList[btnOrderBy.SelectedLabel];
            }
            catch (Exception) { }
            msTimeFrame = String.Empty;
            try
            {
                msTimeFrame = moSupportedTimeFrameList[btnTimeFrame.SelectedLabel];
            }
            catch (Exception) { }

            List<VideoInfo> loListItems;
            if (mbSearchMode)
            {
                Log.Info("Filtering search result");
                //filtering a search result
                if (String.IsNullOrEmpty(msLastSearchCategory))
                {
                    loListItems = ((IFilter)SelectedSite).filterSearchResultList(msLastSearchQuery, miMaxResult, msOrderBy, msTimeFrame);
                }
                else
                {
                    loListItems = ((IFilter)SelectedSite).filterSearchResultList(msLastSearchQuery, msLastSearchCategory, miMaxResult, msOrderBy, msTimeFrame);
                }
            }
            else
            {
                loListItems = ((IFilter)SelectedSite).filterVideoList(msSelectedCategoryValue, miMaxResult, msOrderBy, msTimeFrame);
            }

            UpdateVideoList(loListItems);
            moCurrentVideoList = loListItems;
        }
        private void SearchVideos(String query)
        {
            List<VideoInfo> loListItems = null;
            SelectedSearchCategoryIndex = btnSearchCategories.SelectedItem;
            if (query != String.Empty)
            {
                String category = String.Empty;
                if (moSupportedSearchCategoryList.Count > 1 && !btnSearchCategories.SelectedLabel.Equals("All"))
                {
                    category = moSupportedSearchCategoryList[btnSearchCategories.SelectedLabel];
                    Log.Info("Searching for {0} in category {1}", query, category);
                    msLastSearchCategory = category;
                    loListItems = ((ISearch)SelectedSite).search(query, category);
                }
                else
                {
                    Log.Info("Searching for {0} in all categories ", query);
                    loListItems = ((ISearch)SelectedSite).search(query);
                }
                UpdateVideoList(loListItems);
                mbSearchMode = true;
                moCurrentVideoList = loListItems;
            }
        }
        private void refreshVideoList()
        {
            if (mbSearchMode)
            {
                SearchVideos(msLastSearchQuery);
            }
            else if (showingFavorites)
            {
                DisplayFavoriteVideos();
            }
            else
            {
                List<VideoInfo> loListItems = SelectedSite.getVideoList(msSelectedCategoryValue);
                moCurrentVideoList.Clear();
                //mbSearchMode = false;
                UpdateVideoList(loListItems);
                moCurrentVideoList = loListItems;
            }
        }
        private void DisplayCategoryVideos()
        {
            List<VideoInfo> loListItems;
            //if (fbRefresh)     
            /*{
                if (msSelectedCategoryValue.Contains("{0}"))
                {
                   String lsSearchStr = String.Empty;
                   GetUserInputString(ref lsSearchStr);
                    if (FilterOut(lsSearchStr))
                        {
                            return;
                        }
                        //dlg.SetLine(1, "Searching for \"" + lsSearchStr + "\"");
                        //dlg.SetLine(2, "Please wait...");
                        //dlg.SetLine(3, String.Empty);
                        //dlg.StartModal(GUIWindowManager.ActiveWindow);

                        lsSearchStr = lsSearchStr.Replace(" ", "+");
                  msSelectedCategoryValue = String.Format(msSelectedCategoryValue, lsSearchStr);
                }
                loListItems = SelectedSite.getVideoList(msSelectedCategoryValue);
                moCurrentVideoList.Clear();
                mbSearchMode = false;                
           //}
           
            
            else
            {
             */
            loListItems = moCurrentVideoList;
            //}
            UpdateVideoList(loListItems);
            moCurrentVideoList = loListItems;
        }
        private void DisplayFavoriteVideos()
        {
            List<VideoInfo> loVideoList = ((IFavorite)SelectedSite).getFavorites("gregmac45", "");
            UpdateVideoList(loVideoList);
            moCurrentVideoList = loVideoList;
            showingFavorites = true;
        }
        //private void DisplayCategoryVideos(bool fbRefresh, bool filter,String query)
        private void UpdateVideoList(List<VideoInfo> foVideos)
        {
            GUIDialogProgress dlg = (GUIDialogProgress)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_PROGRESS);
            dlg.SetHeading(PluginName());
            //dlg.SetLine(1, "Loading \"" + msSelectedCategoryName + "\"");
            //dlg.SetLine(2, "Please wait...");
            // dlg.SetLine(3, String.Empty);
            //dlg.StartModal(GUIWindowManager.ActiveWindow);
            //List<VideoInfo> loListItems;
            GUIListItem loListItem;
            GUIControl.ClearControl(GetID, facadeView.GetID);
            loListItem = new GUIListItem("..");
            loListItem.IsFolder = true;
            loListItem.ItemId = 0;
            loListItem.OnItemSelected += new MediaPortal.GUI.Library.GUIListItem.ItemSelectedHandler(OnVideoItemSelected);
            MediaPortal.Util.Utils.SetDefaultIcons(loListItem);
            facadeView.Add(loListItem);
            //facadeView.Clear();
            //GUIListItem loListItem;
            // Check for received data
            if (foVideos.Count == 0)
            {
                // No data received - display errormessage and return
                dlg.PageDestroy();
                GUIDialogOK dlg_error = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK);
                dlg_error.SetHeading(PluginName());
                dlg_error.SetLine(1, "Unable to load data for \"" + msSelectedCategoryName + "\"");
                dlg_error.SetLine(2, String.Empty);
                dlg_error.DoModal(GUIWindowManager.ActiveWindow);
                _CurrentState = State.categories;
                DisplayCategories();
                return;
            }
            List<String> loImageUrlList = new List<string>();
            int liIdx = 0;
            foreach (VideoInfo loVideoInfo in foVideos)
            {
                liIdx++;
                loVideoInfo.Description = cleanString(loVideoInfo.Description);
                if (FilterOut(loVideoInfo.Title) || FilterOut(loVideoInfo.Description))
                {
                    continue;
                }
                loListItem = new GUIListItem(loVideoInfo.Title);
                loListItem.Path = loVideoInfo.VideoUrl;
                loListItem.ItemId = liIdx;
                loListItem.RetrieveArt = false;
                loListItem.OnRetrieveArt += new MediaPortal.GUI.Library.GUIListItem.RetrieveCoverArtHandler(OnRetrieveCoverArt);
                loListItem.OnItemSelected += new MediaPortal.GUI.Library.GUIListItem.ItemSelectedHandler(OnVideoItemSelected);
                facadeView.Add(loListItem);
                //loListItem.RetrieveArt = true;
                loImageUrlList.Add(loVideoInfo.ImageUrl);
                //if (fbRefresh)
                //{
                //    moCurrentVideoList.Add(loVideoInfo);
                //}
            }
            ImageDownloader.getImages(loImageUrlList, OnlineVideoSettings.getInstance().msThumbLocation, facadeView);
            dlg.PageDestroy();
        }
        private void DisplayVideoDetails(VideoInfo foVideo)
        {
            moSelectedVideo = foVideo;
            List<VideoInfo> loVideoList = null;
            try
            {
                loVideoList = SelectedSite.getOtherVideoList(foVideo);
            }
            catch (Exception)
            {
                GUIDialogOK dlg_error = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK);
                dlg_error.SetHeading(PluginName());
                dlg_error.SetLine(1, "Unable to load moviedetails");
                dlg_error.SetLine(2, String.Empty);
                dlg_error.DoModal(GUIWindowManager.ActiveWindow);
                _CurrentState = State.videos;
                DisplayCategoryVideos();
                return;
            }
            moCurrentTrailerList.Clear();
            GUIControl.ClearControl(GetID, facadeView.GetID);
            GUIListItem loListItem = new GUIListItem("..");
            loListItem.IsFolder = true;
            loListItem.ItemId = 0;
            MediaPortal.Util.Utils.SetDefaultIcons(loListItem);
            facadeView.Add(loListItem);
            int liIdx = 0;
            foreach (VideoInfo loVideoInfo in loVideoList)
            {
                liIdx++;
                loVideoInfo.Description = cleanString(loVideoInfo.Description);
                moSelectedVideo.Description = loVideoInfo.Description;
                moSelectedVideo.Other = loVideoInfo.Other;
                loListItem = new GUIListItem(loVideoInfo.Title);
                loListItem.Label2 = loVideoInfo.Title2;
                loListItem.Path = loVideoInfo.VideoUrl;
                loListItem.ItemId = liIdx;
                facadeView.Add(loListItem);
                moCurrentTrailerList.Add(loVideoInfo);
            }
            facadeView.View = GUIFacadeControl.ViewMode.List;
            btnViewAs.Visible = false;
        }
        void OnRetrieveCoverArt(GUIListItem item)
        {
            if (ImageDownloader._imageLocationList.Count > item.ItemId - 1)
            {
                item.ThumbnailImage = ImageDownloader._imageLocationList[item.ItemId - 1];
                //item.OnItemSelected += new MediaPortal.GUI.Library.GUIListItem.ItemSelectedHandler(item_OnItemSelected);
            }
        }
        void OnVideoItemSelected(GUIListItem item, GUIControl parent)
        {
            if (item.ItemId == 0)
            {
                DisplayVideoInfo(null);
            }
            else
            {
                DisplayVideoInfo(moCurrentVideoList[item.ItemId - 1]);
            }
            /*12/16/08
			if(currentView == View.FilmStrip){
				GUIFilmstripControl filmstrip = parent as GUIFilmstripControl;
				if (filmstrip == null)
					return;
				filmstrip.InfoImageFileName = item.ThumbnailImage;
                filmstrip.InfoImageFileName = item.Label;
			}
             * */

        }
        private bool GetUserInputString(ref string sString)
        {
            VirtualKeyboard keyBoard = (VirtualKeyboard)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_VIRTUAL_KEYBOARD);
            keyBoard.Reset();
            keyBoard.IsSearchKeyboard = true;
            keyBoard.Text = sString;
            keyBoard.DoModal(GetID); // show it...
            if (keyBoard.IsConfirmed) sString = keyBoard.Text;
            return keyBoard.IsConfirmed;
        }
        private void Play(VideoInfo foListItem)
        {            
            GUIDialogProgress dlg = (GUIDialogProgress)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_PROGRESS);
            SiteSettings SelectedSiteSettings = moSiteList[msSelectedSiteId];
            dlg.SetHeading(PluginName());
            dlg.SetLine(1, "Connecting to " + SelectedSiteSettings.name);
            dlg.SetLine(2, "Please wait...");
            dlg.SetLine(3, String.Empty);
            dlg.StartModal(GUIWindowManager.ActiveWindow);

            if (mbPlayFullscreen)
            {
                bool playing = false;
                OnlineVideoSettings settings = OnlineVideoSettings.getInstance();
                if (SelectedSite.MultipleFilePlay())
                {
                    PlayList videoList = PlayListPlayer.SingletonPlayer.GetPlaylist(PlayListType.PLAYLIST_VIDEO_TEMP);
                    PlayListItem item;

                    List<String> loUrlList = SelectedSite.getMultipleVideoUrls(foListItem, SelectedSiteSettings);
                    foreach (String url in loUrlList)
                    {
                        if (settings.mbForceMPlayer)
                        {
                            item = new PlayListItem("", url + OnlineVideoSettings.MPLAYER_EXT);
                        }
                        else
                        {
                            item = new PlayListItem("", url);
                        }
                        videoList.Add(item);
                    }
                    PlayListPlayer.SingletonPlayer.CurrentPlaylistType = PlayListType.PLAYLIST_VIDEO_TEMP;
                    if (PlayListPlayer.SingletonPlayer.Play(0))
                    {
                        playing = true;
                    }
                }
                else
                {
                    String lsUrl = SelectedSite.getUrl(foListItem, SelectedSiteSettings);
                    if (String.IsNullOrEmpty(lsUrl))
                    {
                        Log.Info("GUIMusicVideo: Unable to play {0}", lsUrl);
                        GUIDialogNotify dlg2 = (GUIDialogNotify)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
                        dlg2.SetHeading("ERROR");
                        dlg2.SetText("Unable to play the video.");
                        dlg2.DoModal(GUIWindowManager.ActiveWindow);
                        return;
                    }
                    if (settings.mbForceMPlayer && !String.IsNullOrEmpty(lsUrl) && !lsUrl.EndsWith(".wmv"))
                    {
                        if (!lsUrl.EndsWith(".myflv"))
                        {
                            lsUrl = lsUrl + OnlineVideoSettings.MPLAYER_EXT;
                        }
                    }
                    dlg.PageDestroy();
                    if (lsUrl.EndsWith(".wmv"))
                    {
                        if (g_Player.PlayVideoStream(lsUrl))
                            playing = true;
                    }
                    else
                    {
                        if (g_Player.Playing)
                        {
                            g_Player.Stop();
                        }
                        if (settings.mbForceMPlayer)
                        {
                            g_Player.Play(lsUrl, g_Player.MediaType.Video);
                        }
                        else
                        {
                            g_Player.PlayVideoStream(lsUrl, foListItem.Title);
                        }
                        //g_Player.Play("D:\\videos\\test.flv");
                        if (g_Player.Player != null && g_Player.IsVideo)
                        {
                            playing = true;
                            GUIGraphicsContext.IsFullScreenVideo = true;
                            GUIWindowManager.ActivateWindow((int)GUIWindow.Window.WINDOW_FULLSCREEN_VIDEO);
                        }
                    }
                }
            }
        }
        private void playAll()
        {
            bool playing = false;
            PlayList videoList = PlayListPlayer.SingletonPlayer.GetPlaylist(PlayListType.PLAYLIST_VIDEO_TEMP);
            videoList.Clear();
            PlayListItem item;
            OnlineVideoSettings settings = OnlineVideoSettings.getInstance();
            String lsUrl;
            SiteSettings SelectedSiteSettings = moSiteList[msSelectedSiteId];
            List<VideoInfo> loVideoList;
            if (msSelectedSiteId == "15")
            {
                loVideoList = moCurrentTrailerList;
            }
            else
            {
                loVideoList = moCurrentVideoList;
            }
            bool firstAdded = false;
            foreach (VideoInfo loVideo in loVideoList)
            {
                lsUrl = SelectedSite.getUrl(loVideo, SelectedSiteSettings);

                if (settings.mbForceMPlayer && !loVideo.VideoUrl.EndsWith(".wmv"))
                {

                    item = new PlayListItem("", lsUrl + OnlineVideoSettings.MPLAYER_EXT);
                }
                else
                {
                    item = new PlayListItem("", lsUrl);
                }
                videoList.Add(item);
                Log.Info("GUIOnlineVideos.playAll:Added {0} to playlist", loVideo.Title);
                if (!firstAdded)
                {
                    firstAdded = true;
                    PlayListPlayer.SingletonPlayer.CurrentPlaylistType = PlayListType.PLAYLIST_VIDEO_TEMP;
                    if (PlayListPlayer.SingletonPlayer.Play(0))
                    {
                        playing = true;
                    }
                    if (playing)
                    {
                        Log.Info("GUIOnlineVideos.playAll:Playing first video.");
                        GUIGraphicsContext.IsFullScreenVideo = true;
                        GUIWindowManager.ActivateWindow((int)GUIWindow.Window.WINDOW_FULLSCREEN_VIDEO);
                    }
                }
            }
        }
        private void SaveVideo(VideoInfo foListItem)
        {
            SiteSettings SelectedSite = moSiteList[msSelectedSiteId];
            String lsUrl = SiteUtilFactory.getSiteUtil(msSelectedSiteId).getUrl(foListItem, SelectedSite);
            WebClient loClient = new WebClient();
            loClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            loClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCompleted);
            String lsExtension = System.IO.Path.GetExtension(lsUrl);
            String downloadDir = OnlineVideoSettings.getInstance().msDownloadDir;
            if (!downloadDir.EndsWith("/") || !downloadDir.EndsWith("\\"))
            {
                downloadDir += "/";
            }
            String lsFileName = downloadDir + foListItem.Title + "_" + foListItem.Title2 + lsExtension;

            loClient.DownloadFileAsync(new Uri(lsUrl), lsFileName, foListItem.Title);
        }

        private void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            GUIDialogNotify loDlgNotify = (GUIDialogNotify)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
            loDlgNotify.SetText(e.UserState + " Download Complete");
            loDlgNotify.DoModal(GetID);
        }
        private bool FilterOut(String fsStr)
        {
            if (fsStr == String.Empty)
            {
                return false;
            }
            if (msFilterArray != null)
            {
                foreach (String lsFilter in msFilterArray)
                {
                    if (fsStr.IndexOf(lsFilter, StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        Log.Info("Filtering out:{0}\n based on filter:{1}", fsStr, lsFilter);
                        return true;
                        //return false;
                    }
                }
            }
            return false;
        }
        private String cleanString(String fsStr)
        {
            if (fsStr != null)
            {
                // Strip \n's
                fsStr = Regex.Replace(fsStr, @"(\n|\r)", "", RegexOptions.Multiline);

                // Remove whitespace (double spaces)
                fsStr = Regex.Replace(fsStr, @"  +", "", RegexOptions.Multiline);

                // Remove &nbsp;
                fsStr = Regex.Replace(fsStr, @"&nbsp;", " ", RegexOptions.Multiline);


                // Replace <br/> with \n
                fsStr = Regex.Replace(fsStr, @"< *br */*>", "\n", RegexOptions.IgnoreCase & RegexOptions.Multiline);

                // Remove remaining HTML tags
                fsStr = Regex.Replace(fsStr, @"<[^>]*>", "", RegexOptions.Multiline);
            }
            return fsStr;
        }
        private void UpdateViewState()
        {
            Log.Info("Updating View State");
            switch (_CurrentState)
            {
                case State.home:
                    GUIPropertyManager.SetProperty("#header.label", "OnlineVideos");
                    GUIPropertyManager.SetProperty("#header.image", "");
                    if (btnNext != null)
                    {
                        GUIControl.HideControl(GetID, btnNext.GetID);
                    }
                    if (btnPrevious != null)
                    {
                        GUIControl.HideControl(GetID, btnPrevious.GetID);
                    }
                    hideVideoDetails();
                    DisplayVideoInfo(null);
                    HideFilterButtons();
                    HideSearchButtons();
                    currentView = currentSiteView;
                    //Log.Debug("DisplaySites: currentView=" + currentView);
                    SwitchView();
                    break;
                case State.categories:
                    GUIPropertyManager.SetProperty("#header.label", "Categories");
                    GUIPropertyManager.SetProperty("#header.image", "OnlineVidlogo" + msSelectedSiteId + ".jpeg");
                    if (btnNext != null)
                    {
                        GUIControl.HideControl(GetID, btnNext.GetID);
                    }
                    if (btnPrevious != null)
                    {
                        GUIControl.HideControl(GetID, btnPrevious.GetID);
                    }
                    hideVideoDetails();
                    HideFilterButtons();
                    if (SelectedSite is ISearch)
                    {
                        //Log.Info("Showing search buttons");
                        ShowSearchButtons();
                    }
                    if (SelectedSite is IFavorite)
                    {
                        ShowFavoriteButtons();
                    }

                    DisplayVideoInfo(null);
                    currentView = View.List;
                    //Log.Debug("DisplayCategories: currentView=" + currentView);
                    SwitchView();
                    break;
                case State.videos:
                    HideSearchButtons();
                    HideFavoriteButtons();
                    GUIPropertyManager.SetProperty("#header.label", msSelectedCategoryName);
                    GUIPropertyManager.SetProperty("#header.image", "OnlineVidlogo" + msSelectedSiteId + ".jpeg");
                    if (btnNext != null)
                    {
                        GUIControl.ShowControl(GetID, btnNext.GetID);
                    }
                    hideVideoDetails();


                    SelectedSite = SiteUtilFactory.getSiteUtil(msSelectedSiteId);

                    if (SelectedSite is IFilter)
                    {
                        //btnMaxResult.Visible = true;
                        //GUIPropertyManager.SetProperty("#filter.enabled", "!Control.isVisible(50)");
                        ShowFilterButtons();
                    }

                    if (btnNext != null)
                    {
                        if (SelectedSite.hasNextPage())
                        {
                            GUIControl.EnableControl(GetID, btnNext.GetID);
                        }
                        else
                        {
                            GUIControl.DisableControl(GetID, btnNext.GetID);
                        }
                    }
                    if (btnPrevious != null)
                    {
                        GUIControl.ShowControl(GetID, btnPrevious.GetID);

                        if (SelectedSite.hasPreviousPage())
                        {
                            GUIControl.EnableControl(GetID, btnPrevious.GetID);
                        }
                        else
                        {
                            GUIControl.DisableControl(GetID, btnPrevious.GetID);
                        }
                    }
                    currentView = currentVideoView;
                    //Log.Debug("DisplayCategoryVideos: currentView=" + currentView);
                    SwitchView();

                    DisplayVideoInfo(null);
                    break;
                case State.info:

                    GUIPropertyManager.SetProperty("#header.label", moSelectedVideo.Title);
                    GUIPropertyManager.SetProperty("#header.image", "OnlineVidlogo" + msSelectedSiteId + ".jpeg");
                    if (btnNext != null)
                    {
                        GUIControl.HideControl(GetID, btnNext.GetID);
                    }
                    if (btnPrevious != null)
                    {
                        GUIControl.HideControl(GetID, btnPrevious.GetID);
                    }
                    showVideoDetails();

                    HideFilterButtons();
                    HideSearchButtons();
                    DisplayVideoInfo(null);
                    break;
            }
            //GUIControl.DeSelectControl(GetID, btnViewAs.GetID);
            //GUIControl.SelectControl(GetID, facadeView.GetID);
            GUIControl.UnfocusControl(GetID, btnViewAs.GetID);
            GUIControl.FocusControl(GetID, facadeView.GetID);


        }
        private void hideVideoDetails()
        {
            GUIControl.HideControl(GetID, 23);
            GUIControl.HideControl(GetID, 24);
            GUIControl.HideControl(GetID, 25);
            GUIControl.HideControl(GetID, 54);
            GUIControl.HideControl(GetID, 55);
            GUIControl.HideControl(GetID, 56);
            GUIControl.HideControl(GetID, 57);
            GUIControl.HideControl(GetID, 58);
            GUIControl.HideControl(GetID, 59);
        }
        private void showVideoDetails()
        {
            GUIControl.ShowControl(GetID, 23);
            GUIPropertyManager.SetProperty("#movieposter", ImageDownloader.downloadPoster(moSelectedVideo.ImageUrl.Replace("_m", "_l"), moSelectedVideo.Title, OnlineVideoSettings.getInstance().msThumbLocation));
            GUIPropertyManager.SetProperty("#movietitle", moSelectedVideo.Title);
            GUIPropertyManager.SetProperty("#trailerdesc", moSelectedVideo.Description);
            ITMSClient.TrailerInfo info = (ITMSClient.TrailerInfo)moSelectedVideo.Other;
            GUIPropertyManager.SetProperty("#genre", info.Genre);
            GUIPropertyManager.SetProperty("#releasedate", info.Release);
            GUIControl.ShowControl(GetID, 24);
            GUIControl.ShowControl(GetID, 25);
            GUIControl.ShowControl(GetID, 54);
            GUIControl.ShowControl(GetID, 55);
            GUIControl.ShowControl(GetID, 56);
            GUIControl.ShowControl(GetID, 57);
            GUIControl.ShowControl(GetID, 58);
            GUIControl.ShowControl(GetID, 59);
        }
        private void HideFilterButtons()
        {

            Log.Info("Hiding Filter buttons");
            //disable the buttons to allow remote navigation
            GUIControl.DisableControl(GetID, btnMaxResult.GetID);
            GUIControl.DisableControl(GetID, btnOrderBy.GetID);
            GUIControl.DisableControl(GetID, btnTimeFrame.GetID);
            GUIControl.DisableControl(GetID, btnUpdate.GetID);

            GUIControl.HideControl(GetID, btnMaxResult.GetID);
            GUIControl.HideControl(GetID, btnOrderBy.GetID);
            GUIControl.HideControl(GetID, btnTimeFrame.GetID);
            GUIControl.HideControl(GetID, btnUpdate.GetID);


        }

        private void ShowFilterButtons()
        {
            Log.Info("Showing Filter buttons");
            btnMaxResult.Clear();
            btnOrderBy.Clear();
            btnTimeFrame.Clear();

            moSupportedMaxResultList = ((IFilter)SelectedSite).getResultSteps();
            foreach (int step in moSupportedMaxResultList)
            {
                GUIControl.AddItemLabelControl(GetID, btnMaxResult.GetID, step + "");
            }
            moSupportedOrderByList = ((IFilter)SelectedSite).getOrderbyList();
            foreach (String orderBy in moSupportedOrderByList.Keys)
            {
                GUIControl.AddItemLabelControl(GetID, btnOrderBy.GetID, orderBy);
            }
            moSupportedTimeFrameList = ((IFilter)SelectedSite).getTimeFrameList();
            foreach (String time in moSupportedTimeFrameList.Keys)
            {
                GUIControl.AddItemLabelControl(GetID, btnTimeFrame.GetID, time);
            }

            GUIControl.ShowControl(GetID, btnMaxResult.GetID);
            GUIControl.ShowControl(GetID, btnOrderBy.GetID);
            GUIControl.ShowControl(GetID, btnTimeFrame.GetID);
            GUIControl.ShowControl(GetID, btnUpdate.GetID);

            //enabled the buttons
            GUIControl.EnableControl(GetID, btnMaxResult.GetID);
            GUIControl.EnableControl(GetID, btnOrderBy.GetID);
            GUIControl.EnableControl(GetID, btnTimeFrame.GetID);
            GUIControl.EnableControl(GetID, btnUpdate.GetID);

            if (SelectedMaxResultIndex > -1)
            {
                GUIControl.SelectItemControl(GetID, btnMaxResult.GetID, SelectedMaxResultIndex);
            }
            if (SelectedOrderByIndex > -1)
            {
                GUIControl.SelectItemControl(GetID, btnOrderBy.GetID, SelectedOrderByIndex);
            }
            if (SelectedTimeFrameIndex > -1)
            {
                GUIControl.SelectItemControl(GetID, btnTimeFrame.GetID, SelectedTimeFrameIndex);
            }
        }
        private void HideSearchButtons()
        {
            Log.Info("Hiding Search buttons");

            //disable the buttons to allow remote navigation
            GUIControl.DisableControl(GetID, btnSearchCategories.GetID);
            GUIControl.DisableControl(GetID, btnSearch.GetID);

            GUIControl.HideControl(GetID, btnSearchCategories.GetID);
            GUIControl.HideControl(GetID, btnSearch.GetID);
        }

        private void ShowSearchButtons()
        {
            Log.Info("Showing Search buttons");
            btnSearchCategories.Clear();
            moSupportedSearchCategoryList = ((ISearch)SelectedSite).getSearchableCategories();
            GUIControl.AddItemLabelControl(GetID, btnSearchCategories.GetID, "All");
            foreach (String category in moSupportedSearchCategoryList.Keys)
            {
                GUIControl.AddItemLabelControl(GetID, btnSearchCategories.GetID, category);
            }
            if (moSupportedSearchCategoryList.Count > 1)
            {
                GUIControl.ShowControl(GetID, btnSearchCategories.GetID);
                GUIControl.EnableControl(GetID, btnSearchCategories.GetID);
            }
            GUIControl.ShowControl(GetID, btnSearch.GetID);
            GUIControl.EnableControl(GetID, btnSearch.GetID);
            if (SelectedSearchCategoryIndex > -1)
            {
                Log.Info("restoring search category...");
                GUIControl.SelectItemControl(GetID, btnSearchCategories.GetID, SelectedSearchCategoryIndex);
                Log.Info("Search category restored to " + btnSearchCategories.SelectedLabel);
            }
        }
        private void HideFavoriteButtons()
        {
            Log.Info("Hiding Search buttons");
            //disable the buttons to allow remote navigation
            GUIControl.DisableControl(GetID, btnFavorite.GetID);
            GUIControl.HideControl(GetID, btnFavorite.GetID);
        }
        private void ShowFavoriteButtons()
        {
            GUIControl.ShowControl(GetID, btnFavorite.GetID);
            GUIControl.EnableControl(GetID, btnFavorite.GetID);
        }

        private void ChangeFacadeView()
        {
            switch (currentView)
            {
                case View.List:
                    currentView = View.Icons;
                    break;
                case View.Icons:
                    currentView = View.LargeIcons;
                    break;
                case View.LargeIcons:
                    //currentView = View.FilmStrip;
                    currentView = View.List;
                    break;
                //case View.FilmStrip:
                //	currentView = View.List;
                //	break;
            }
            if (_CurrentState == State.home)
            {
                currentSiteView = currentView;
            }
            else if (_CurrentState == State.videos)
            {
                currentVideoView = currentView;
            }
            SwitchView();
        }
        protected void SwitchView()
        {
            if (facadeView == null)
            {
                return;
            }
            string strLine = String.Empty;
            switch (currentView)
            {
                case View.List:
                    facadeView.View = GUIFacadeControl.ViewMode.List;
                    strLine = GUILocalizeStrings.Get(101);
                    break;
                case View.Icons:
                    facadeView.View = GUIFacadeControl.ViewMode.SmallIcons;
                    strLine = GUILocalizeStrings.Get(100);
                    break;
                case View.LargeIcons:
                    facadeView.View = GUIFacadeControl.ViewMode.LargeIcons;
                    strLine = GUILocalizeStrings.Get(417);
                    break;
                //               case View.Album:
                //                 facadeView.View = GUIFacadeControl.ViewMode.Filmstrip;
                //               strLine = GUILocalizeStrings.Get(733);
                //break;
            }
            GUIControl.SetControlLabel(GetID, btnViewAs.GetID, strLine);
        }
        private void DisplayVideoInfo(VideoInfo foVideo)
        {
            if (foVideo == null || msSelectedSiteId == "15")
            {
                GUIPropertyManager.SetProperty("#videotitle", String.Empty);
                GUIPropertyManager.SetProperty("#tags", String.Empty);
                GUIPropertyManager.SetProperty("#length", String.Empty);
                GUIPropertyManager.SetProperty("#desc", String.Empty);
            }
            else
            {
                GUIPropertyManager.SetProperty("#videotitle", foVideo.Title);
                if (String.IsNullOrEmpty(foVideo.Tags))
                {
                    GUIPropertyManager.SetProperty("#tags", "None");
                }
                else
                {
                    GUIPropertyManager.SetProperty("#tags", foVideo.Tags);
                }
                if (String.IsNullOrEmpty(foVideo.Length))
                {
                    GUIPropertyManager.SetProperty("#length", "None");
                }
                else
                {
                    double ldLength;
                    if (Double.TryParse(foVideo.Length, out ldLength))
                    {
                        TimeSpan t = TimeSpan.FromSeconds(ldLength);
                        GUIPropertyManager.SetProperty("#length", t.ToString());
                    }
                    else
                    {
                        GUIPropertyManager.SetProperty("#length", foVideo.Length);
                    }
                }
                if (String.IsNullOrEmpty(foVideo.Description))
                {
                    GUIPropertyManager.SetProperty("#desc", "None");
                }
                else
                {
                    GUIPropertyManager.SetProperty("#desc", foVideo.Description);
                }
            }
        }
        private void AddOrRemoveFavorite(VideoInfo loSelectedVideo)
        {
            SiteSettings SelectedSiteSettings = moSiteList[msSelectedSiteId];


            if (SelectedSite is IFavorite)
            {
                if (SelectedSiteSettings.password == String.Empty || SelectedSiteSettings.username == String.Empty)
                {
                    GUIDialogOK dlg_error = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK);
                    dlg_error.SetHeading(PluginName());
                    dlg_error.SetLine(1, "Please set your username and password in the Configuration");
                    dlg_error.SetLine(2, String.Empty);
                    dlg_error.DoModal(GUIWindowManager.ActiveWindow);
                }
                else
                {
                    if (showingFavorites)
                    {
                        Log.Info("Received request to add video to favorites.");
                        ((IFavorite)SelectedSite).removeFavorite(loSelectedVideo, SelectedSiteSettings.username, SelectedSiteSettings.password);
                    }
                    else
                    {
                        ((IFavorite)SelectedSite).addFavorite(loSelectedVideo, SelectedSiteSettings.username, SelectedSiteSettings.password);
                    }
                }

            }
            else
            {
                if (showingFavorites)
                {
                    SelectedSite.RemoveFavorite(loSelectedVideo);
                }
                else
                {
                    SelectedSite.AddFavorite(loSelectedVideo, msSelectedSiteId);
                }
            }
            refreshVideoList();
        }
        private void getRelatedVideos(VideoInfo loSelectedVideo)
        {
            moCurrentVideoList = SelectedSite.getRelatedVideos(loSelectedVideo.VideoUrl);
            DisplayCategoryVideos();
        }
        #endregion
    }
}
